import { Button, DatePicker, Layout, message, Modal, Select, Space, Spin } from "antd";
import style from './index.module.css';
import { Fragment, useEffect, useState } from "react";
import { addAccountAPI, deleteAccountAPI, filterAccountAPI, getCategoryAPI, IAddAccount, IUpdateAccount, updateAccountAPI } from "../../api";
import { AccountType, IAccount, ICategory } from "../../interface";
import locale from 'antd/es/date-picker/locale/zh_CN';
import moment from "moment";
import CategoryCommit from "../categoryCommit";
import AccountTable from "../accountTable";
import AccountCommit, { IFormData } from "../accountCommit";


const { Header, Content } = Layout;
const { Option } = Select;

const AccountMain: React.FC = () => {

    const [category, setCategory] = useState<ICategory[]>([]);
    const [account, setAccount] = useState<IAccount[]>([]);

    const [categoryLoading, setCategoryLoading] = useState(false);

    const [queryCategory, setQueryCategory] = useState<number>();
    const [queryDate, setQueryDate] = useState<Date>(new Date());

    const [limit, setLimit] = useState(1);
    const [total, setTotal] = useState(0);


    const [addCategoryModalVisible, setAddCategoryModalVisible] = useState(false);


    // 提交修改
    const postUpdateAccount = async (params: IUpdateAccount) => {
        return new Promise<boolean>((resolve, reject) => {
            updateAccountAPI(params)
            .then(res => {
                // console.log(res)
                if (res.data.code !== 0) {
                    throw new Error(res.data.message)
                }
                getFilterAccount(1);
                resolve(true);
            })
            .catch(e => {
                console.log('修改数据提交发生错误')
                console.log(e)
                message.error(e.message)
                reject(false)
            })
        })
    }
    // 提交删除
    const postDeleteAccount = (account: IAccount) => {
        return new Promise<boolean>((resolve, reject) => {
            deleteAccountAPI(account.account_id)
            .then(res => {
                // console.log(res)
                if (res.data.code !== 0) {
                    throw new Error(res.data.message);
                }
                getFilterAccount(1);
                resolve(true);
            })
            .catch(e => {
                console.log('category获取发生错误')
                console.log(e)
                message.error(e.message);
                reject(false)
            })
        })
    }
    // 提交添加
    const postAddAccount = (params: IAddAccount) => {
        return new Promise<boolean>((resolve, reject) => {
            addAccountAPI(params)
            .then(res => {
                // console.log(res)
                if (res.data.code !== 0) {
                    throw new Error(res.data.message);
                }
                getFilterAccount(1);
                resolve(true);
            })
            .catch(e => {
                console.log('category获取发生错误')
                console.log(e)
                message.error(e.message);
                reject(false)
            })
        })
    }

    // 获取查询搜索后的account
    const getFilterAccount = (limit: number) => {
        filterAccountAPI(limit, queryCategory, queryDate)
        .then(res => {
            // console.log(res)
            if (res.data.code === 0) {
                const { total, accounts } = res.data.data;
                setAccount(accounts)
                setTotal(total);
            } else {
                throw new Error(res.data.message);
            }
        })
        .catch(e => {
            console.log('category获取发生错误')
            console.log(e)
            message.error(e.message);
        })
    }
    // 获取所有category分类
    const getCategory = () => {
        setCategoryLoading(true);
        getCategoryAPI()
        .then(res => {
            // console.log(res)
            if (res.data.code === 0) {
                setCategory(res.data.data)
            } else {
                throw new Error(res.data.message);
            }
        })
        .catch(e => {
            console.log('category获取发生错误')
            console.log(e)
            message.error(e.message);
        })
        .finally(() => {
            setCategoryLoading(false);
        });
    }


    // 获取账目分类
    useEffect(() => {
        getCategory();
    }, []);
    // 获取账目
    useEffect(() => {
        getFilterAccount(1);
    }, []);


    // 账目查询
    const accountQuery = () => {
        setLimit(1);
        getFilterAccount(1);
    }
    // 查询重置
    const accountQueryReset = () => {
        // 每次查询页数从1开始
        setLimit(1);
        // 两个选择框重置
        setQueryCategory(undefined);
        setQueryDate(new Date());
    }
    // 关闭modal弹框
    const closeModal = (isCommit: boolean) => {
        setAddCategoryModalVisible(false);
        // 触发了修改或者添加
        if (isCommit) {
            getFilterAccount(limit);
            getCategory();
        }
    }
    // 添加账单
    const addAccountModal = () => {
        const onOk = async (data: IFormData) => {
            // 加载弹出框,防止多次点击
            modal.update(pre => ({
                ...pre,
                content: (
                    <Fragment>
                        <Spin className="loading" />
                        <AccountCommit submitFrom={onOk} cancel={onCancel} />
                    </Fragment>
                ),
            }))
            // 表单数据处理成可提交的数据
            let date_time = new Date(data.date_time.toDate());
            let account_type = data.account_type ? AccountType.expend : AccountType.income;
            await postAddAccount({...data, account_type, date_time});
            modal.destroy();
        }
        const onCancel = () => {
            modal.destroy();
        }
        const modal = Modal.confirm({
            icon: '',
            content: (
                <Fragment>
                    <AccountCommit submitFrom={onOk} cancel={onCancel} />
                </Fragment>
            ),
            cancelButtonProps: {style: {display: 'none'}},
            okButtonProps: {style: {display: 'none'}},
        })
    }


    return (
        <Layout className={style.account}>
            <Header className={style.account_header}>
                <Space wrap={true}>
                    <DatePicker 
                        locale={locale} 
                        className={style.account_datepicker} 
                        value={moment(queryDate)}
                        onChange={(date, dateString) => setQueryDate(new Date(dateString))} 
                        picker="month" 
                        allowClear={false}
                        style={{minWidth: 120}}
                    />

                    <Select 
                        className={style.account_category_select} 
                        placeholder="选择分类"
                        allowClear={true} 
                        value={queryCategory}
                        loading={categoryLoading}
                        onChange={v => setQueryCategory(v)} 
                    >
                        {
                            category.map(item => (<Option key={item.category_id} value={item.category_id}>{item.category_name}</Option>))
                        }
                    </Select>
                        
                    <Button type="primary" onClick={accountQuery}>查询</Button> 
                    <Button onClick={accountQueryReset}>重置</Button>
                    <Button onClick={addAccountModal}>添加账单</Button>
                    <Button onClick={() => setAddCategoryModalVisible(true)}>分类管理</Button>
                </Space>
            </Header>
            <Content className={style.account_content}>
                <AccountTable 
                    data={account}
                    total={total}
                    handleDelete={postDeleteAccount}
                    handleUpdate={postUpdateAccount}
                    handlePageChange={page => getFilterAccount(page)}
                />
            </Content>
            
            <CategoryCommit show={addCategoryModalVisible} closeFunc={closeModal} />
        </Layout>            
    )
}

export default AccountMain;

